//
//  TaskDetailsViewController.m
//  TableViewApp
//
//  Created by Dmitriy on 05.06.13.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "TaskDetailsViewController.h"
#import "TaskCollector.h"


enum textFieldStates
{
    Editable = 1,
    NonEditable = 2
};


@implementation TaskDetailsViewController 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    if(taskForEditing==nil)
    {
        taskForEditing = [[Task alloc] initWithName:@"Enter task name" time:[NSDate date]];
        taskIsNew = YES;
    }
    [self fillFields];
    if(taskIsNew)
    {
        [self editTask:changeStateButton];
    }
    else
    {
        [self switchFields:NO];
    }
    taskDate = [taskForEditing taskTime];
    [self registerForKeyboardNotifications];
    taskDatePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    taskDateField.inputView = taskDatePicker;
//    UIView* accessoryView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
//    [accessoryView setAlpha: 0.8];
//
//    UIButton *btnDone = [UIButton buttonWithType: UIButtonTypeRoundedRect];
//    
//    [btnDone setFrame: CGRectMake(240, 0, 80, 40)];
//    [btnDone setTitle: @"Done" forState: UIControlStateNormal];
//    
//    [btnDone addTarget: self action: @selector(dateIsEntered:) forControlEvents: UIControlEventTouchUpInside];
//    [accessoryView addSubview:btnDone];
    
    UIView* accessoryView = [[[NSBundle mainBundle] loadNibNamed:@"TaskEditingInputAccessoryView" owner:self options:nil] objectAtIndex:0];
    
    taskDateField.inputAccessoryView = accessoryView;
    
    
    
    detailsScrollView.contentSize = CGSizeMake(detailsScrollView.frame.size.width, taskNotificationSwitch.frame.origin.y+taskNotificationSwitch.frame.size.height);
                            
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self unregisterForKeyboardNotifications];
    [taskForEditing release];
    [taskDate release];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewWillAppear:(BOOL)animated
{
    [self fillFields]; 
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void) setEditingTask:(Task *)task
{
    taskForEditing = [task retain];
}
-(void) dealloc
{
    [taskForEditing release];
    [super dealloc];
}
-(void)fillFields
{
    taskNameField.text = [taskForEditing taskName];
    taskDateField.text = [NSDateFormatter localizedStringFromDate:[taskForEditing taskTime] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
    taskNotificationSwitch.on = [taskForEditing hasNotification];
    if (taskForEditing.notificationInterval!=-1) {
        taskNotificationSwitch.on = YES;
        taskNotificationTime.hidden = NO;
        taskNotificationTimeCaption.hidden = NO;
        taskNotificationTime.text = [NSDateFormatter localizedStringFromDate:[taskForEditing notificationTime] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
    }
    else {
        taskNotificationSwitch.on = NO;
        taskNotificationTime.hidden = YES;
        taskNotificationTimeCaption.hidden = YES;
    }
}
-(void) switchFields:(BOOL)state
{
    taskNameField.borderStyle = state? UITextBorderStyleRoundedRect : UITextBorderStyleNone;
    taskNameField.enabled = state;
    taskDateField.enabled = state;
    taskDateField.borderStyle = state? UITextBorderStyleRoundedRect : UITextBorderStyleNone;
//    taskNotificationSwitch.enabled = state;
    taskNotificationTime.borderStyle = state? UITextBorderStyleRoundedRect : UITextBorderStyleNone;
    taskNotificationTime.enabled = state;
}
-(void) changeBarButton:(id)button
               WithText:(NSString*)text
           WithSelector:(SEL)selector
{
    UIBarButtonItem* barItem = (UIBarButtonItem*)button;
//    barItem = [[UIBarButtonItem alloc]initWithTitle:text style:UIBarButtonItemStyleBordered target:nil action:selector];
    [barItem setTitle:text];
    [barItem setAction:selector]; 
}
-(IBAction)editTask:(id)sender
{
    [self switchFields:YES];
    [self changeBarButton:sender WithText:@"Save" WithSelector:@selector(saveTask:)];

}
-(IBAction)saveTask:(id)sender
{
    [self switchFields:NO];
    [self changeBarButton:sender WithText:@"Edit" WithSelector:@selector(editTask:)];
    if(taskIsNew)
    {
        [[TaskCollector sharedInstance] appendTask:taskForEditing];
        taskIsNew = NO;
    }
    
    [taskForEditing modifyWithName:taskNameField.text WithTime:taskDate];
    
//    if(taskNotificationSwitch.isOn!=taskForEditing.hasNotification) [taskForEditing toggleNotification];
    [self fillFields];
}

//-(IBAction)notificationSwitched:(id)sender
//{
//    [taskForEditing toggleNotification];
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [taskNameField resignFirstResponder];
}
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

- (void)unregisterForKeyboardNotifications
{
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWasShown:)
//                                                 name:UIKeyboardDidShowNotification object:nil];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(keyboardWillBeHidden:)
//                                                 name:UIKeyboardWillHideNotification object:nil];
//    
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    detailsScrollView.contentInset = contentInsets;
    detailsScrollView.scrollIndicatorInsets = contentInsets;
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    detailsScrollView.contentInset = contentInsets;
    detailsScrollView.scrollIndicatorInsets = contentInsets;
}
- (IBAction)dateIsEntered:(id)sender
{
//    UIDatePicker *taskDatePicker = (UIDatePicker*)sender;
    taskDate = [taskDatePicker date];
    taskDateField.text = [NSDateFormatter localizedStringFromDate:taskDate dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterShortStyle];
    [taskDateField resignFirstResponder];
}

- (IBAction)notificationStateChanged:(id)sender
{
    if(taskNotificationSwitch.isOn)
    {
        [self performSegueWithIdentifier:@"NotificationTime" sender:taskNotificationSwitch]; 
    }
    else
    {
        taskForEditing.notificationInterval = -1;
    }
}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    [self saveTask:changeStateButton];
    [segue.destinationViewController setEditingTask:taskForEditing];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField.tag==Editable) {
        return YES;
    }
    else
    {
        [self performSegueWithIdentifier:@"NotificationTime" sender:taskNotificationSwitch]; 
        return NO;
    }
}

@end
